import { useEffect } from 'react'
import { useAppDispatch, useAppSelector } from '../hooks'
import { useLocation, useSearchParams } from 'react-router-dom'
import { useDebounce } from './useDebounce'
import { searchSlice } from '../store/reducers/slices/searchSlice'
import { selectSearch } from '../store/reducers/selectors'
import { paginationSlice } from '../store/reducers/slices/paginationSlice'

type TUseSearch = {
	searchInput: string | null
}

export const useSearch = ({ searchInput }: TUseSearch) => {
	const search = useAppSelector(selectSearch)
	const dispatch = useAppDispatch()
	const location = useLocation()
	const [searchParams, setSearchParams] = useSearchParams()
	const initialSearchParam = searchParams.get('search')

	const searchDebounce = useDebounce({ value: searchInput, delay: 1000 }) || ''
	// Если search пуст, а в initialSearchParam есть данные, значит осуществлялся переход по ссылке, записываем значение в state
	if (!search && initialSearchParam)
		dispatch(searchSlice.actions.setSearch(searchDebounce))

	useEffect(() => {
		//  Поиск работает только для страницы catalog
		if (location.pathname === '/catalog') {
			// если searchParam пуст, то удаляем searchParam из url
			if (searchDebounce === '') {
				searchParams.delete('search')
				setSearchParams(searchParams)
			} else {
				searchParams.set('search', searchDebounce)
				setSearchParams(searchParams)
			}
		}

		dispatch(searchSlice.actions.setSearch(searchDebounce))
		dispatch(paginationSlice.actions.setPage(1))
	}, [
		searchParams,
		dispatch,
		initialSearchParam,
		location.pathname,
		searchDebounce,
		setSearchParams,
	])
	return initialSearchParam
}
